<template>
	<view class="sign-dialog">
		<view class="sign-content">
			<view class="close-view" @click="onClose">
				<image src="/static/close-da.png" class="close-image"></image>
			</view>
			<swiper class="swiper-view" @change="(event) => swiperIndex = event.detail.current">
				<swiper-item v-for="(item, index) in entity.clientSignSayingList" :key="index">
					<view class="swiper-item">
						<view class="title-view">
							<view class="time-text">
								<view class="day-text">{{getDate('DD')}}</view>
								<view class="month-text">/ {{getDate('MM')}} {{getDate('YYYY')}}</view>
							</view>
							<view class="title-text">今日已签到</view>
						</view>
						<image :src="`${IMG_URL}${item.coverImg}`" class="swiper-image" mode="aspectFill"></image>
						<view class="swiper-content">
							<view class="swiper-division">
								{{swiperIndex + 1}}/{{entity.clientSignSayingList.length}}
							</view>
							<view class="content-text">
								{{item.title}}
							</view>
							<view class="user-view">
								<view class="user-info">
									<image :src="`${IMG_URL}${entity.avatarImg}`" mode="aspectFill" class="user-image">
									</image>
									<view class="user-name">{{entity.nickName}}</view>
								</view>
								<image src="/static/logo.png" mode="aspectFill" class="code-image"></image>
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
			<view class="button-view">
				<view class="button-item" @click="onPoster">
					<image src="/static/download-one-icon.png" class="button-icon"></image>
					<view>保存海报</view>
				</view>
			</view>
		</view>
		<!-- <button @click="canvasInfo">保存海报</button> -->
		<canvas canvas-id="poster" id="poster" class="poster-canvas"></canvas>
	</view>
</template>

<script>
	import dayjs from 'dayjs';
	export default {
		props: {
			entity: Object
		},
		data() {
			return {
				swiperIndex: 0
			}
		},
		methods: {
			async onPoster() {
				const posterEntity = this.entity.clientSignSayingList[this.swiperIndex]
				let context = uni.createCanvasContext('poster', this);
				const element = await this.querySelectElement()
				const entity = this.entity.clientSignSayingList[this.swiperIndex]
				// const bgImage =  await this.downloadFile(`${this.IMG_URL}${entity.coverImg}`)
				context.drawImage('/static/pc/poster-bg.png', 0, 0, element.width, element.height);
				this.roundRect(context, 0, 0, element.width, 59, [6, 0], 'rgba(255,255,255,0.9)')
				this.roundRect(context, 0, element.height - 144, element.width, 144, [6, 6], 'rgba(255,255,255,0.9)')
				context.font = '600 16px PingFangSC'
				context.setFontSize(16)
				const title = '今日已签到'
				const textWidth = context.measureText(title)
				context.setFillStyle("#333")
				context.fillText(title, element.width - textWidth.width - 20, 35)
				context.save();
				context.fillText(`${this.getDate('DD')}`, 20, 35)
				context.save();
				context.font = '400 12px PingFangSC'
				context.setFontSize(12)
				context.fillText(`/ ${this.getDate('MM')} ${this.getDate('YYYY')}`, 45, 35)
				context.save();
				const desc = posterEntity.title
				const descArr = this.drawText(context, desc, element.width - 32)
				let descHeight = element.height - 124
				descArr.forEach((item, index) => {
					if (index > 2) return
					context.fillText(item, 12, descHeight)
					descHeight += 20
				})
				this.drawRound(context, '/static/pc/poster-bg.png', 35, element.height - 35, 25)
				context.font = '600 16px PingFangSC'
				context.setFontSize(16)
				context.fillText(this.entity.nickName, 70, element.height - 30)
				context.save();
				this.drawRound(context, '/static/pc/poster-bg.png', element.width - 45, element.height - 45, 35)
				// context.fillText(desc, 12, element.height - 124)
				context.draw(true, (dres) => {
					if (dres.errMsg != 'drawCanvas:ok') return
					uni.canvasToTempFilePath({
						canvasId: 'poster',
						success: (res) => {
							if (res.errMsg != 'canvasToTempFilePath:ok') return;
							this.saveImage(res.tempFilePath)
						},
						fail: () => {
							uni.showToast({
								title: '生成海报失败!',
								icon: "none"
							})
						},
						complete: () => uni.hideLoading(),
					})
				})
			},
			saveImage(filePath) {
				uni.saveImageToPhotosAlbum({
					filePath,
					success: async () => {
						await uni.$util.showSuccess('保存成功')
						this.onClose()
					},
					fail: () => uni.hideLoading()
				});
			},
			drawRound(ctx, img, x, y, r) {
				ctx.save()
				let d = r * 2;
				let cx = x - r;
				let cy = y - r;
				ctx.beginPath();
				ctx.arc(x, y, r, 0, 2 * Math.PI);
				ctx.closePath();
				ctx.clip();
				ctx.drawImage(img, cx, cy, d, d);
				ctx.restore();
			},
			drawText(ctx, str, canvasWidth) {
				let [lineWidth, textStr, textList] = [0, '', []]
				for (let i = 0; i < str.length; i++) {
					textStr += str[i]
					if (ctx.measureText(textStr).width >= canvasWidth) {
						textList.push(textStr)
						textStr = '';
					}
					if (i == str.length - 1) {
						textList.push(textStr)
						textStr = '';
					}
				}
				return textList
			},
			roundRect(ctx, x, y, w, h, radius, color = '#FFFFFF') {
				const [tr, dr] = radius
				ctx.save()
				// 开始绘制
				ctx.beginPath()
				// 因为边缘描边存在锯齿，最好指定使用 transparent 填充
				// 这里是使用 fill 还是 stroke都可以，二选一即可
				ctx.setFillStyle(color)
				// ctx.setStrokeStyle('transparent')
				// 左上角
				ctx.arc(x + tr, y + tr, tr, Math.PI, Math.PI * 1.5)
				// border-top
				ctx.moveTo(x + tr, y)
				ctx.lineTo(x + w - tr, y)
				ctx.lineTo(x + w, y + tr)
				// 右上角
				ctx.arc(x + w - tr, y + tr, tr, Math.PI * 1.5, Math.PI * 2)

				// border-right
				ctx.lineTo(x + w, y + h - dr)
				ctx.lineTo(x + w - dr, y + h)
				// 右下角
				ctx.arc(x + w - dr, y + h - dr, dr, 0, Math.PI * 0.5)

				// border-bottom
				ctx.lineTo(x + dr, y + h)
				ctx.lineTo(x, y + h - dr)
				// 左下角
				ctx.arc(x + dr, y + h - dr, dr, Math.PI * 0.5, Math.PI)
				// border-left
				ctx.lineTo(x, y + tr)
				ctx.lineTo(x + tr, y)
				// 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
				ctx.fill()
				// ctx.stroke()
				ctx.closePath()
				// 剪切
				ctx.clip()
				ctx.restore()
			},
			querySelectElement() {
				return new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query.select('#poster').boundingClientRect(data => resolve(data)).exec();
				})
			},
			downloadFile(url) {
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url,
						success: (res) => resolve(res.tempFilePath)
					})
				})
			},
			onClose() {
				this.$emit('close')
			},
			getDate(format) {
				if (format == 'MM') {
					const monthEun = {
						'01': 'Jan',
						'02': 'Feb',
						'03': 'Mar',
						'04': 'Apr',
						'05': 'May',
						'06': 'Jun',
						'07': 'Jul',
						'08': 'Aug',
						'09': 'Sep',
						'10': 'Oct',
						'11': 'Nov',
						'12': 'Dec',
					}
					const month = dayjs().format(format)
					return monthEun[month]
				}
				return dayjs().format(format)
			}
		}
	}
</script>

<style scoped lang="scss">
	.sign-dialog {
		width: 100%;
		height: 100vh;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 30;
		background: rgba($color: #000000, $alpha: 0.9);
		@extend .column;
		justify-content: flex-start;
		padding-top: 176upx;

		.poster-canvas {
			position: fixed;
			left: -1000px;
			top: -1000px;
			width: 580rpx;
			height: calc(100vh - 500upx);
			// background: rgba($color: #fff, $alpha: 0.2);
		}

		.sign-content {
			width: 580rpx;
			height: calc(100vh - 500upx);
			position: relative;
			border-radius: 12upx;

			.close-view {
				width: 70upx;
				height: 70upx;
				position: absolute;
				right: 0;
				top: -100upx;

				.close-image {
					width: 100%;
					height: 100%;
				}
			}

			.button-view {
				width: 100%;
				@extend .column;
				position: absolute;
				bottom: -150upx;
				left: 0;

				.button-item {
					@extend .row;
					width: 471rpx;
					height: 91rpx;
					border-radius: 45rpx;
					border: 1rpx solid #FFFFFF;
					font-size: 29rpx;
					color: #FFFFFF;

					.button-icon {
						width: 29upx;
						height: 31upx;
						margin-right: 18upx;
					}
				}

			}

			.swiper-view {
				width: 100%;
				height: 100%;

				.swiper-item {
					width: 100%;
					height: 100%;
					position: relative;

					.title-view {
						width: 100%;
						height: 118rpx;
						padding: 0 40upx;
						background: rgba(255, 255, 255, 0.9);
						@extend .row-between;
						position: absolute;
						top: 0;
						left: 0;
						z-index: 2;
						border-radius: 12upx 12upx 0 0;

						.time-text {
							@extend .row;
							align-items: baseline;

							.day-text {
								font-weight: 600;
								font-size: 33rpx;
								color: #282726;
							}

							.month-text {
								font-size: 24rpx;
								color: #282726;
								margin-left: 10upx;
							}
						}

						.title-text {
							font-weight: 600;
							font-size: 33rpx;
							color: #282726;
						}
					}

					.swiper-image {
						width: 100%;
						height: 100%;
						border-radius: 12upx;
					}

					.swiper-content {
						width: 100%;
						height: 288rpx;
						background: rgba(255, 255, 255, 0.9);
						padding: 22upx;
						position: absolute;
						left: 0;
						bottom: 0;
						z-index: 2;
						@extend .column;
						justify-content: space-between;
						border-radius: 0 0 12upx 12upx;

						.swiper-division {
							position: absolute;
							left: 0;
							top: -40upx;
							background: rgba(6, 0, 0, 0.9);
							padding: 5upx 10upx;
							font-size: 22rpx;
							color: #FFFFFF;
						}

						.content-text {
							width: 100%;
							font-size: 25rpx;
							color: #282726;
						}

						.user-view {
							width: 100%;
							@extend .row-between;

							.user-info {
								@extend .row;

								.user-image {
									width: 65upx;
									height: 65upx;
									border-radius: 50%;
								}

								.user-name {
									margin-left: 22upx;
									font-weight: 600;
									font-size: 33rpx;
									color: #282726;
								}
							}

							.code-image {
								width: 116upx;
								height: 116upx;
							}
						}
					}
				}
			}
		}
	}
</style>